<template>
  <div class="box">
    <!--搜索与重置-->
    <el-form ref="form" label-width="100px" :model="query">
      <el-row>
        <el-col :md="8" :xl="6">
          <el-form-item label="输入框：" prop="name">
            <el-input v-model="query.name" placeholder="输入框" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :md="8" :xl="6">
          <el-form-item label="输入框：" prop="name">
            <el-input v-model="query.resource" placeholder="输入框" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :md="8" :xl="6">
          <el-form-item label="选择日期：" prop="startDate">
            <el-date-picker
              v-model="query.startDate"
              type="date"
              class="full-width-important"
              value-format="yyyy-mm-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="8" :xl="6">
          <el-form-item label="下拉选择：" prop="type">
            <el-select v-model="query.type" placeholder="下拉选择" class="full-width" clearable>
              <el-option
                v-for="item in energyList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :md="8" :xl="6">
          <el-form-item label-width="20px">
            <el-button type="primary" icon="el-icon-search" @click="handleCurrentChange(1)">
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--操作行-->
    <div class="mb-15">
      <el-button type="success" icon="el-icon-circle-plus-outline" @click="editStaff('')">
        新增员工
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="!multipleSelection.length">
        删除员工
      </el-button>
      <el-button v-preventReClick v-permission="['admin']" type="warning" icon="el-icon-download" @click="exportExcel">
        导出excel
      </el-button>
    </div>
    <!--表格-->
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="tableData"
      border
      element-loading-text="加载中..."
      class="table"
      stripe
      :cell-class-name="cellClassName"
      header-cell-class-name="table-header"
      @cell-click="cellClick"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" fixed width="50" align="center"></el-table-column>
      <el-table-column type="index" fixed label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="name" min-width="180" label="员工姓名"></el-table-column>
      <el-table-column prop="position" min-width="180" label="员工职位"
                       :formatter="formatterPosition"></el-table-column>
      <el-table-column prop="iPhone" min-width="110" label="联系方式"></el-table-column>
      <el-table-column prop="createdTime" min-width="160" label="入职时间"></el-table-column>
      <el-table-column prop="remark" label="备注" min-width="300" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160">
        <template v-slot="scope">
          <el-button type="primary" size="mini" @click="editStaff(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      background
      :current-page="query.pageNo"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import { getCommList, exportItemExcel } from '@/api/user'

const positionList = [
  { id: '1', name: '前端开发' },
  { id: '2', name: '后端开发' },
  { id: '3', name: '测试' },
  { id: '4', name: '运维' }
]

export default {
  name: 'Table',
  data() {
    return {
      /* 搜索条件 */
      query: {
        pageNo: 1,
        pageSize: 10,
        name: '',
        startDate: ''
      },
      loading: false,
      tableData: [],
      total: 0,
      multipleSelection: [],
      energyList: []
    }
  },
  created() {
    this.getList()
    this.searchWelfare()
  },
  methods: {
    // 每页 val 条
    handleSizeChange(val) {
      this.query.pageNo = 1
      this.query.pageSize = val
      this.searchWelfare()
    },
    // 当前页: val
    handleCurrentChange(val) {
      this.query.pageNo = val
      this.searchWelfare()
    },
    // 查询tableData列表信息
    searchWelfare() {
      this.loading = true
      setTimeout(() => {
        this.tableData = [
          {
            id: '1001',
            name: '张三',
            position: '1',
            iPhone: '15149174852',
            createdTime: '2022-11-12 10:36:42',
            remark: '前端'
          },
          {
            id: '1002',
            name: '李四',
            position: '2',
            iPhone: '18953895241',
            createdTime: '2019-01-30 09:58:21',
            remark: '测试'
          },
          {
            id: '1003',
            name: '王五',
            position: '3',
            iPhone: '13214004656',
            createdTime: '2020-05-10 09:15:36',
            remark: '目前，随着 css 变量、css 函数越来越多；css 嵌套草案的实施；以及，预处理工具开发者疏于维护'
          },
          {
            id: '1004',
            name: '赵六',
            position: '4',
            iPhone: '13141548596',
            createdTime: '2021-10-02 09:26:45',
            remark: '运维'
          }
        ]
        this.total = 4
        this.loading = false
      }, 300)
    },
    // 重置搜索条件
    resetSearch() {
      this.$refs['form'].resetFields()
      this.handleSizeChange(10)
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 新增/编辑
    editStaff(id) {
      this.$router.push({
        path: '/example/table-add',
        query: { id }
      })
    },
    // 获取comm常量数据
    getList() {
      getCommList({ code: 'ENERGY_TYPE' }).then(response => {
        this.energyList = response
      }).catch(error => {
        console.log('error', error)
      })
    },
    // 将数组中的每一个对象所需的值分别作为对象中的键与值
    formatterPosition(row) {
      // 逗号表达式
      // eslint-disable-next-line no-sequences
      const obj = positionList.reduce((obj, item) => (obj[item.id] = item.name, obj), {})
      return obj[row.position] || '-'
    },
    // 某个单元格被点击时会触发该事件
    cellClick(row, column) {
      if (column.property === 'name') {
        this.$router.push({
          path: '/example/table-detail',
          query: { id: row.id }
        })
      }
    },
    // 一列单元格class回调
    cellClassName({ row, column }) {
      if (column.property === 'name') {
        return 'default-color pointer'
      }
    },
    // 导出excel
    exportExcel() {
      exportItemExcel({ type: 2 }).then(response => {
        this.exportMethod(response, '测试导出')
      }).catch(() => {
      })
    },
    // 下载excel的方法（公用）
    exportMethod(response, tempName) {
      const tempDate = '2020-12-12' // 获取当前日期
      const blob = new Blob([response])
      const fileName = tempName + '_' + tempDate + '.xlsx'
      if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }
  }
}
</script>

<style scoped></style>
